package com.tfxy.hxl.controller;

import com.tfxy.hxl.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/file")
public class FileController {

    @Value("${file.upload.path:./uploads/}")
    private String uploadPath;

    @Value("${file.upload.url-prefix:/uploads/}")
    private String urlPrefix;
    @PostMapping("/upload")
    public R uploadFile(@RequestParam("file") MultipartFile file) {
        System.out.println("开始处理文件上传请求");
        System.out.println("上传路径配置: " + uploadPath);
        System.out.println("URL前缀配置: " + urlPrefix);
        
        if (file.isEmpty()) {
            System.out.println("文件为空");
            return R.error().message("文件为空");
        }

        System.out.println("文件信息: " + file.getOriginalFilename() + ", 大小: " + file.getSize() + " bytes");

        // 检查文件类型
        String contentType = file.getContentType();
        System.out.println("文件类型: " + contentType);
        if (contentType == null || !contentType.startsWith("image/")) {
            System.out.println("文件类型不支持: " + contentType);
            return R.error().message("只能上传图片文件");
        }

        // 检查文件大小（限制为5MB）
        if (file.getSize() > 5 * 1024 * 1024) {
            System.out.println("文件大小超限: " + file.getSize());
            return R.error().message("文件大小不能超过5MB");
        }

        try {
            // 确保上传路径是绝对路径
            File uploadDir = new File(uploadPath);
            if (!uploadDir.isAbsolute()) {
                // 如果是相对路径，转换为绝对路径
                uploadDir = new File(System.getProperty("user.dir"), uploadPath);
            }
            
            System.out.println("上传目录: " + uploadDir.getAbsolutePath());
            
            // 创建上传目录
            if (!uploadDir.exists()) {
                boolean created = uploadDir.mkdirs();
                System.out.println("创建目录结果: " + created);
                if (!created) {
                    return R.error().message("无法创建上传目录");
                }
            }

            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String extension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            String filename = UUID.randomUUID().toString() + extension;
            System.out.println("生成文件名: " + filename);

            // 保存文件
            File destFile = new File(uploadDir, filename);
            System.out.println("目标文件路径: " + destFile.getAbsolutePath());
            
            file.transferTo(destFile);
            System.out.println("文件保存成功");

            // 返回文件URL
            String fileUrl = urlPrefix + filename;
            System.out.println("返回文件URL: " + fileUrl);
            
            return R.ok().data("url", fileUrl).data("filename", filename);

        } catch (IOException e) {
            System.err.println("文件上传异常: " + e.getMessage());
            e.printStackTrace();
            return R.error().message("文件上传失败: " + e.getMessage());
        } catch (Exception e) {
            System.err.println("未知异常: " + e.getMessage());
            e.printStackTrace();
            return R.error().message("文件上传失败: " + e.getMessage());
        }
    }
} 